from django.core.management.base import BaseCommand, CommandError
from apps.order.models import *
from apps.message.models import *
from apps.product.models import *
from apps.repo.models import *
from datetime import timedelta
import time
from django.db import transaction
import sys

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('product_id', type=str)
        parser.add_argument('count', type=int)
        parser.add_argument('repo_id', type=str)
        parser.add_argument('parent_type', type=str)

    def handle(self, *args, **options):
        start_time = time.time()
        product_id = options.get('product_id')
        repo_id = options.get('repo_id')
        repo_parent_type = options.get('parent_type')
        count = options.get('count')

        if repo_parent_type == "a":
            su_parent_type = StoreUnit.ParentType.CROWD_BOX_V1.name
        elif repo_parent_type == "b":
            su_parent_type = StoreUnit.ParentType.CHEST_V1.name
        else:
            raise Exception('Parent Type Error')

        unique_code_version = GoodsBlock.UniqueCodeVersion.DOG_YEAR_SPRING.name
        trade_type = GoodsBlock.TradeType.PRE_SALE.name

        product = Product.objects.get(pk=product_id)
        fields = product.get_unique_code()

        generated_gbs = []
        generated_gb_chains = []

        last_gb = GoodsBlock.objects.filter(product=product).last()
        if last_gb:
            last_no_int_fields = last_gb.get_no_int_fields()
        else:
            last_no_int_fields = None
        for i in range(count):
            su = StoreUnit.get_free_unit(repo_id, su_parent_type)
            if not su:
                raise Exception("无空闲存储空间")
            next_no_int_fields = GoodsBlock.get_next_no_int_fields(last_no_int_fields)
            if next_no_int_fields is None:
                break
            next_no_fields = [chr(next_no_int_fields[k]) if k in [0, 1] else int_2_2d(next_no_int_fields[k]) for k in
                              range(len(next_no_int_fields))]
            no = ''.join(next_no_fields)
            gb = GoodsBlock(
                product=product,
                unique_code=''.join(fields + [no, ]),
                unique_code_version=unique_code_version,
                repo_id=repo_id,
                store_unit_id=su.pk,
                trade_type=trade_type,
                no=no,
                fields=fields,
                trade_price=product.pre_sale_price,
                avg_price=product.pre_sale_price,
                trade_datetime=datetime.now(),
            )
            # 入库节点
            gbc = GoodsBlockChain(
                goods_block=gb,
                operator_user_id=None,
                chain_type=GoodsBlockChain.ChainType.IN_REPO.name,
                node_datetime=datetime.now(),
                storage_repo_id=repo_id,
                storage_repo_days=0
            )
            gbc_op = gbc.get_block_chain_node_outputs()
            gbc.title = gbc_op['title']
            gbc.contents = gbc_op['contents']
            gbc.repo_info = gbc_op['repo_info']

            generated_gbs.append(gb)
            generated_gb_chains.append(gbc)
            su.in_use = True
            su.save()
            last_no_int_fields = copy.copy(next_no_int_fields)
        with transaction.atomic():
            GoodsBlock.objects.bulk_create(generated_gbs)
            GoodsBlockChain.objects.bulk_create(generated_gb_chains)
        end_time = time.time()
        print('Count: %d Success: %d Times: %f' % (count, len(generated_gbs), end_time-start_time))
